﻿using CommonTools;
using CommonTools.Controls;
using Newtonsoft.Json;
using shop.Bll;
using shop.Bll.cost;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace shop.cost
{
    public partial class PostCalcStrategyEditor : Form
    {
        PostCalcStrategyBll _bll = new PostCalcStrategyBll();


        public PostCalcStrategyEditor()
        {
            InitializeComponent();


            cl_AddWeight.ValueType = typeof(decimal);
            cl_maxWei.ValueType = typeof(decimal);
        }

        private async void btnOk_Click(object sender, EventArgs e)
        {

            var list = new List<PostCalcStrategy>();

            foreach (DataGridViewRow row in this.grid_stock.Rows)
            {
                if(row.IsNewRow)
                {
                    break;
                }

                PostCalcStrategy item;
                if (row.Tag is PostCalcStrategy cs)
                {
                    item = cs;
                }
                else
                {
                    item = new PostCalcStrategy();
                }
                item.isdel = false;
                item.isDetails = false;
                item.Name = row.Cells[cl_name.Index].Value.IsNull();

                list.Add(item);
            }

            var subItems = list
                .Where(a=> a.Items != null)
                .SelectMany(a=> a.Items)
                .ToList();

            list.AddRange(subItems);

            Result res = await _bll.SaveItems(list);

            if (res.ErrorCode != ResultCode.Ok)
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private  void btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

  

        private void PostCalcStrategyEditor_Load(object sender, EventArgs e)
        {
          
        }


        private async void grid_stock_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            if(e.Row.Tag  is PostCalcStrategy cs)
            {
                await _bll.DeleteItems(cs.Name);
            }
        }

        private async void gridSpec_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            if (e.Row.Tag is PostCalcStrategy cs)
            {
                await _bll.DeleteItems(cs.id);

                if (grid_stock.SelectedCells.Count > 0)
                {
                    var doc = grid_stock.Rows[grid_stock.SelectedCells[0].RowIndex].Tag as PostCalcStrategy;
                    if(doc.Items != null && doc.Items.Contains(cs))
                    {
                        doc.Items.Remove(cs);
                    }
                }
            }
        }

        private int _lastRow =-1;

        private async void grid_stock_SelectionChanged(object sender, EventArgs e)
        {
            if(this.grid_stock.SelectedCells.Count<=0)
            {
                return;
            }

            if(_lastRow == grid_stock.SelectedCells[0].RowIndex)
            {
                return;
            }

            _lastRow = grid_stock.SelectedCells[0].RowIndex;
            grid2.Rows.Clear();

            if (grid_stock.Rows[_lastRow].Tag is PostCalcStrategy item)
            {
                if (item.Items == null)
                {
                    var name = grid_stock[cl_name.Index, _lastRow].Value.IsNull();

                    item.Items = await _bll.GetItems(item.Name);
                }
                this.grid2.AddItems(item.Items,
                    a => a.MaxWeight,
                    a => a.AddWeight);
            }
            else if(grid_stock.Rows[_lastRow].IsNewRow == false)
            {
                var name = grid_stock[cl_name.Index, _lastRow].Value.IsNull();
                if(string.IsNullOrEmpty(name) == false)
                {
                    var find = await _bll.Query(name);
                    if (find.Any())
                    {
                        grid_stock.Rows[_lastRow].Tag = find.FirstOrDefault();
                        find.FirstOrDefault().Items = await _bll.GetItems(name);
                        this.grid2.AddItems(find.FirstOrDefault().Items,
                            a => a.MaxWeight,
                            a => a.AddWeight);
                    }
                }
     
            }
        }


        private void grid2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if(e.RowIndex<0 || e.ColumnIndex<0)
            {
                return;
            }

            if(grid_stock.SelectedCells.Count<=0)
            {
                MessageBox.Show("请先选择右侧的一个策略", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var name = grid_stock[cl_name.Index, grid_stock.SelectedCells[0].RowIndex].Value.IsNull();
            if(string.IsNullOrEmpty(name))
            {
                MessageBox.Show("请先选择右侧的一个策略", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var doc = grid_stock.Rows[grid_stock.SelectedCells[0].RowIndex].Tag as PostCalcStrategy;


            PostCalcStrategy item;
            if (grid2.Rows[e.RowIndex].Tag is PostCalcStrategy cs)
            {
                item = cs;
            }
            else
            {
                item = new PostCalcStrategy() { isdel=false, isDetails= true};
                grid2.Rows[e.RowIndex].Tag = item;
                if (doc.Items == null)
                    doc.Items = new List<PostCalcStrategy>();
                
                doc.Items.Add(item);
            }

            item.Name = name;
            if(e.ColumnIndex == cl_AddWeight.Index)
            {
                item.AddWeight = grid2[e.ColumnIndex, e.RowIndex].Value.IsNull(0m);
                _changed = true;
            }
            else if (e.ColumnIndex == cl_maxWei.Index)
            {
                item.MaxWeight = grid2[e.ColumnIndex, e.RowIndex].Value.IsNull(0m);
                _changed = true;
            }


        }


        bool _changed = false;

        private void grid_stock_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }

            PostCalcStrategy item;
            if (grid_stock.Rows[e.RowIndex].Tag is PostCalcStrategy cs)
            {
                item = cs;
            }
            else
            {
                item = new PostCalcStrategy() { isdel=false, isDetails= false};
                grid_stock.Rows[e.RowIndex].Tag = item;
            }

            item.Name = grid_stock[e.ColumnIndex, e.RowIndex].Value.IsNull();
            _changed = true;
        }

        private async void PostCalcStrategyEditor_Shown(object sender, EventArgs e)
        {
            var items = await _bll.Query(null);

            this.grid_stock.AddItems(items,
                a => a.Name);
        }
    }
}
